import { createRouter, createWebHashHistory, createWebHistory, RouteRecordRaw } from "vue-router";

// 通过Vite的import.meta.glob()方法实现自动化导入路由
const mainRouterModules = import.meta.glob('../layout/*.vue')
const viewRouterModules = import.meta.glob('../views/**/*.vue')

// 子路由
const childRoutes = Object.keys(viewRouterModules).map((path)=>{	
	const childName = path.match(/\.\.\/views\/(.*)\.vue$/)[1].split('/')[1];
	console.log('%cindex.ts line:10 childName', 'color: #007acc;', childName);
	return {
		path: `/${childName.toLowerCase()}`,
		name: childName,
		component: viewRouterModules[path]
	} 
})

// 根路由
const rootRoutes = Object.keys(mainRouterModules).map((path) => {
    const name = path.match(/\.\.\/layout\/(.*)\.vue$/)[1].toLowerCase();
    const routePath = `/${name}`;
    if (routePath == '/index') {
		return {
			path: '/',
			name,
			redirect: '/home',
			component: mainRouterModules[path],
			children: childRoutes,
			meta: {
				permission: true,
				keepAlive:true
			},
		};
    }else{
		return {
			path: routePath,
			name,
			component: mainRouterModules[path],
			meta: {
				permission: true,
				keepAlive:true
			},
			
		};
	}
})

const routes: Array<RouteRecordRaw> = rootRoutes

const router = createRouter({
    history: createWebHistory(),
    routes,
});
router.beforeEach((to, from, next) => {
    document.title = `joinca | 中卡`;
	console.log('%cindex.ts line:56 childRoutes', 'color: #007acc;', childRoutes);
    const role = localStorage.getItem('userInfo');
	console.log(`output->to.path`,to.path)
	// next()
    if (to.path != '/home') {
		next('/home');
    } 
	else {
        next();
    }
});

export default router







